mui.init();

var $objs = {
	title: $("#title"),
	price: $("#price"),
	priceDiff: $("#priceDiff"),
	priceDiffRate: $("#priceDiffRate"),
	open: $("#open"),
	close: $("#close"),
	high: $("#high"),
	low: $("#low"),
	chart: null,
	buyPrice: $("#buyPrice"),
	sellPrice: $("#sellPrice")
};
var dataGoods, $wvOpen, $wvTrade, isline = true, chartLastTime,
	chartRange = 1,
	lineColor = "#eeeeee",
	chartColor = {
		up: 'rgb(240,85,83)',
		down: 'rgb(47,186,63)'
	};
var DATETIME_LABEL_FORMAT = {
		second: "%H:%M:%S",
		minute: "%H:%M",
		hour: "%H:%M",
		day: "%m-%d",
		week: "%m-%d",
		month: "%Y-%m",
		year: "%Y"
	},
	COLOR_ON = {
		candlestick: {
			color: "#2FBA3F",
			upColor: "#ffffff",
			lineColor: "#2FBA3F",
			upLineColor: "#F05553"
		},
		close: {
			color: "#e06c00"
		}
	},
	COLOR_OFF = {
		candlestick: {
			color: "invalid",
			upColor: "invalid",
			lineColor: "invalid",
			upLineColor: "invalid"
		},
		close: {
			color: "invalid"
		}
	},
	COLOR = {
		candlestick: $.extend({}, COLOR_ON.candlestick),
		close: $.extend({}, COLOR_OFF.close)
	};

formatOHLCData = function(k, t) {
	//console.log(k);
	var candlestick, close, close_price, cur, high, i, low, open, time, trend, vol, volume, _i, _len, _ref;
	for(_ref = [
			[],
			[],
			[]
		], volume = _ref[0], candlestick = _ref[1], close_price = _ref[2], i = _i = 0, _len = k.length; _len > _i; i = ++_i) {
		cur = k[i], time = cur[0], open = cur[1], high = cur[2], low = cur[3], close = cur[4], vol = cur[5], trend = t == 1 ? (i >= 1 ? this.checkTrend(k[i - 1], cur) : !0) : open < close,
			close_price.push([time, close]), candlestick.push([time, open, high, low, close]), volume.push({
				x: time,
				y: vol,
				color: (trend ? chartColor.up : chartColor.down)
			});
	}
	return {
		candlestick: candlestick,
		volume: volume,
		close: close_price
	}
}

var isRefresh = false, lastOHLCData;
refreshChart = function() {
	window.setTimeout(function() {
		if(!isRefresh) {
			isRefresh = true;
			if($objs.chart) {
				var series;
				app.post("GetOHLC", {
					GoodsID: dataGoods.GoodsID,
					Tick: chartRange,
					UnixTime: chartLastTime
				}, function(data) {					
					if(!isRefresh || lastOHLCData == data){
						return;
					}
					
					lastOHLCData = data;
					data = formatOHLCData(eval(data));
					chartLastTime = data.close[data.close.length-1][0];
					
					if(isline) {
						series = $objs.chart.series[1];
						data.close.forEach(function(v, i) {
							series.points.filter(function(p) {
								return p.x == v[0];
							}).forEach(function(v) {
								v.remove();
							});
							series.addPoint(v);
						})
					} else {
						//refreshKlineChart.process($objs.chart, data);
						series = $objs.chart.series[0];
						data.candlestick.forEach(function(v, i) {
							series.points.filter(function(p) {
								return p.x == v[0];
							}).forEach(function(v) {
								v.remove();
							});
							series.addPoint(v);

						})
					}
					
					isRefresh=false;
				});
			}
			//refreshChart();
		}
	}, 10000);
}

buildOHLCChart = function(data) {
	if(data.length == 0) return;
	isRefresh = false;
	data = formatOHLCData(eval(data));	
	chartLastTime = data.close[data.close.length-1][0];
	
	if($objs.chart){
		console.log("a");
		$objs.chart.series[0].setData(data.candlestick);
		$objs.chart.series[0].setVisible(!isline);
		$objs.chart.series[1].setData(data.close);
		$objs.chart.series[1].setVisible(isline);
		return;
	}

	$objs.chart = new Highcharts.StockChart({
		chart: {
			renderTo: "chart",
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 0,
			marginLeft: 0,
			marginTop: 0
		},
		credits: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		navigator: {
			enabled: false
		},
		scrollbar: {
			enabled: false
		},
		rangeSelector: {
			enabled: false
		},
		loading: {
			style: {
				backgroundColor: 'inherit',
				opacity: 1
			}
		},
		xAxis: {
			offset: 0,
			type: "datetime",
			dateTimeLabelFormats: DATETIME_LABEL_FORMAT,
			lineColor: lineColor,
			tickColor: lineColor,
			tickWidth: 1,
			//tickPixelInterval: 80,
			minTickInterval:2,
			labels: {
				style: {
					'color': '#aaaaaa'
				}
			}
		},
		yAxis: [{
			showFirstLabel: true,
			showLastLabel: true,
			tickColor: lineColor,
			gridLineColor: lineColor,
			opposite: true,
			plotLines: [{
				value: 0,
				width: 1,
				color: lineColor
			}],
			offset: 0,
			//opposite: false,
			labels: {
				//align: 'left', x: 5, y: 5,
				formatter: function() {
					return this.value.toFixed(2);
				},
				style: {
					'color': '#aaaaaa'
				}
			},
			height: '100%',
			lineColor: lineColor,
			//gridLineColor: lineColor,
			lineWidth: 1
		}],
		tooltip: {
			shared: true,
			crosshairs: true,
			valueDecimals: 2,
			borderWidth: 1,
			borderColor: '#ffffff',
			//backgroundColor: "rgba(0,0,0,0)",
			borderRadius: 2,
			//shadow: !1,
			shared: !0,
			split: true,
			formatter: function() {
				return Highcharts.dateFormat('%Y-%m-%d %H:%M', this.x) + '<br/>' +
					Highcharts.numberFormat(this.y, 2);
			}
		},
		series: [
			$.extend({
				id: "candlestick",
				name: "指数",
				type: "candlestick",
				data: data.candlestick,
				visible: !isline
			}, COLOR_ON.candlestick),
			$.extend({
				id: "close",
				name: "指数",
				type: "spline",
				data: data.close,
				lineWidth: 1,
				marker: {
					radius: 0
				},
				visible: isline
			}, COLOR_ON.close)
		]
	});
}

bindChart = function() {	
	app.post("GetOHLC", {
		GoodsID: dataGoods.GoodsID,
		Tick: chartRange,
		UnixTime: 0
	}, function(data) {
		buildOHLCChart(data);
	});
}

window.addEventListener('init', function(e) {
	dataGoods = e.detail;
	bindData();
});

window.addEventListener('market', function(e) {
	var data = e.detail;
	pushMarket(data);
});

window.addEventListener('chart', function(e) {
	console.log(e.detail);
	buildOHLCChart(e.detail);
});

mui("#range").on('tap', 'li', function() {
	chartRange = this.getAttribute("data-tab");
	removeChildClass($id("range"), "li", "selected");
	addClass(this, "selected");

	if(chartRange == 1) {
		isline = true;
	} else {
		isline = false;
	}

	bindChart();
});

$id("list").addEventListener('tap', function() {
	mui.openWindow({
		url: "trade-item-info.html",
		id: "trade-item-info",
		extras: {
			data: dataGoods
		}
	});
});

$id("btnSell").addEventListener('tap', function() {
	openTrade(resources.ContractType.Sell);
});

$id("btnBuy").addEventListener('tap', function() {
	openTrade(resources.ContractType.Buy);
});

pushMarket = function(data) {
	if(dataGoods && data.GoodsID == dataGoods.GoodsID) {
		$objs.buyPrice.text(data.buyPrice1.toFixed(1));
		$objs.sellPrice.text(data.sellPrice1.toFixed(1));
		 
		$objs.price.text(data.price.toFixed(1));
		
		var diff = data.price - data.pclose;
		$objs.priceDiff.text(diff.toFixed(2));
		$objs.priceDiffRate.text((diff / data.pclose * 100).toFixed(2) + "%");
		if(diff > 0){
			$objs.price.parent().addClass("price-up-text")
			$objs.price.parent().removeClass("price-down-text")
		}
		else if(diff < 0){
			$objs.price.parent().addClass("price-down-text")
			$objs.price.parent().removeClass("price-up-text")
		}
		
		$objs.high.text(data.high);
		$objs.low.text(data.low);		
	}

	window.setTimeout(function() {
		mui.fire($wvOpen, "pullMarket", data);
	}, 100);
}

openTrade = function(type) {
	if(!app.isLogin()) {
		app.openLogin();
		return false;
	}

	dataGoods.ContractType = type;
	window.setTimeout(function() {
		mui.fire($wvOpen, "show", dataGoods);
	}, 1);
	$wvOpen.show("pop-in");
};

bindData = function() {
	$objs.title.text(dataGoods.GoodsName);
	$objs.open.text(dataGoods.open);
	$objs.close.text(dataGoods.pclose);

	pushMarket(dataGoods);

	setTimeout(function () {
		refreshChart();		
	},10);
};

mui.plusReady(function() {
	$wvOpen = mui.preload({
		id: "trade-open",
		url: "trade-open.html"
	});
});